package com.jinlejia.erp.ui.home;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.jinlejia.erp.BuildConfig;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.base.unicorn.UnicornUtils;
import com.jinlejia.erp.databinding.FragmentHomeBinding;
import com.jinlejia.erp.ui.access_manager.AccessManagerActivity;
import com.jinlejia.erp.ui.common.GuideDialog;
import com.jinlejia.erp.ui.common.MainActivity;
import com.jinlejia.erp.ui.customer.RecordCustomer1Activity;
import com.jinlejia.erp.ui.house.HouseRecordAddressActivity;
import com.jinlejia.erp.ui.house.prospect.SearchCoreSellActivity;
import com.jinlejia.erp.ui.message.MessageActivity;
import com.jinlejia.erp.ui.mine.calculator.CalculatorActivity;
import com.jinlejia.erp.ui.mine.client.ClientListActivity;
import com.jinlejia.erp.ui.mine.contract.ContractAuditCoverActivity;
import com.jinlejia.erp.ui.new_house.house.NewHouseActivity;
import com.jinlejia.erp.utils.ACache;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.SharePTool;
import com.jinlejia.erp.widget.CenterAlignImageSpan;
import com.jinlejia.feedback.idea.ui.FbIdeaMainActivity;
import com.jinlejia.feedback.idea.ui.QuestionResponseActivity;
import com.lab.kit.StringKit;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.nimlib.utils.NimIMUtils;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import me.nereo.multi_image_selector.MultiImageSelector;
import okhttp3.Call;
import okhttp3.MediaType;

import static android.app.Activity.RESULT_OK;


public class HomeFragment extends Fragment implements MainActivity.HomeFragmentIsShowListener {
    private FragmentHomeBinding binding;
    private ArrayList<String> mSelectPath = new ArrayList<>();
    private ArrayList<Map<String, Object>> noticeList = new ArrayList<>();
    private View view;

    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_home, container, false);
            binding = DataBindingUtil.bind(view);
            binding.setEvent(this);
            initView();
        }
        // 缓存的rootView需要判断是否已经被加过parent，
        // 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        return view;
    }

    private void initView() {
        if (BuildConfig.bbsActivity == null) {
            binding.navMessageImageView.setVisibility(View.GONE);
        } else {
            binding.navMessageImageView.setVisibility(View.VISIBLE);
        }
        SharePTool.UserInfoBean userInfoBean = SharePTool.getUserInfoBean(getContext());
        if (TextUtils.isEmpty(userInfoBean.getTitleLevel()) || TextUtils.isEmpty(userInfoBean.getShareStoreName())) { //如果没有用户信息
            loadUserInfo(); //则请求服务器获取用户的信息
        } else { //根据用户职务进行判断用户是否有`意见反馈`的权限
            String titleLevel = userInfoBean.getTitleLevel();
            if ("城市总经理".equals(titleLevel)) {
                binding.questionreplyTextView.setVisibility(View.VISIBLE);
            } else {
                binding.questionreplyTextView.setVisibility(View.GONE);
            }
            UnicornUtils.registerUnicorn(userInfoBean);
        }
        OkHttpUtils
                .postString()
                .url(ApiConfig.NOTICE_INDEX)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content("")
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(getActivity(), response, null)) {
                            //数据列表  {"data":[{"noticeTitle":"测试推送","id":176,"newFlag":1}],"message":"操作成功","code":"200"}
                            noticeList = JSON.parseObject(response.get("data").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            List<CharSequence> infoList = new ArrayList<>();
                            for (int i = 0; i < noticeList.size(); i++) {
                                if (noticeList.get(i).get("newFlag").equals(1)) {
                                    SpannableString ss = new SpannableString("ss " + noticeList.get(i).get("noticeTitle").toString());
                                    if (isAdded()) {
                                        Drawable drawable = getResources().getDrawable(R.mipmap.ic_news_red);
                                        int drawHeight = drawable.getMinimumHeight();
                                        int drawWidth = drawable.getMinimumWidth();
                                        drawable.setBounds(0, 0, drawWidth, drawHeight);
                                        CenterAlignImageSpan imageSpan = new CenterAlignImageSpan(drawable);
                                        ss.setSpan(imageSpan, 0, 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                                        infoList.add(ss);
                                    }
                                } else {
                                    infoList.add(noticeList.get(i).get("noticeTitle").toString());
                                }
                            }
                            if (infoList.size() > 1) {
                                binding.marqueeView.startWithList(infoList);
                            } else {
                                infoList.addAll(infoList);
                                binding.marqueeView.startWithList(infoList);
                                binding.marqueeView.stopFlipping();
                            }
                        }
                    }
                });
        binding.marqueeView.setOnItemClickListener((position, textView) -> {
            Intent intent = new Intent(getActivity(), NoticeDetailActivity.class);
            intent.putExtra("id", noticeList.get(position).get("id").toString());
            startActivity(intent);
        });

    }

    private void loadUserInfo() {
        OkHttpUtils
                .get()
                .url(ApiConfig.PERSONAL_INFO)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if ("200".equals(String.valueOf(response.get("code")))) {
                            JSONObject json = JSON.parseObject(String.valueOf(response.get("data")));
                            //region 保存用户信息
                            String imageUrl = String.valueOf(json.get("imageUrl"));
                            String userName = json.getString("name");
                            String telNum = json.getString("tel");
                            String titleLevel = json.getString("titleLevel");
                            String email = json.getString("email");
                            String deptName = json.getString("deptName");
                            String shareStoreName = json.getString("shareStoreName");

                            SharePTool.UserInfoBean bean = new SharePTool.UserInfoBean();
                            bean.setImageUrl(imageUrl);
                            bean.setEmail(email);
                            bean.setTelNum(telNum);
                            bean.setTitleLevel(titleLevel);
                            bean.setDeptName(deptName);
                            bean.setUserName(userName);
                            bean.setShareStoreName(shareStoreName);
                            SharePTool.UserInfoBean infoBean = SharePTool.saveUserInfoBean(getContext(), bean);
                            UnicornUtils.registerUnicorn(infoBean);
                            //endregion

                            if ("城市总经理".equals(titleLevel)) {
                                binding.questionreplyTextView.setVisibility(View.VISIBLE);
                            } else {
                                binding.questionreplyTextView.setVisibility(View.GONE);
                            }
                        }
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        //指引弹出层
        if (TextUtils.isEmpty(ACache.get(getActivity()).getAsString("home_guide")))
            new GuideDialog(getContext(), "home_guide", R.mipmap.guide_home).show();

    }

    public void toMessageActivity(View view) {
        MessageActivity.start(getContext());
    }


    public void onClick(View view) {
        Intent mIntent = null;
        switch (view.getId()) {
            case R.id.homeSearch:                  //搜索(默认查询出售楼盘)
                mIntent = new Intent(getActivity(), SearchCoreSellActivity.class);
                mIntent.putExtra("type", "shs");
                EventBus.getDefault().post("", "TAG_HOME_SEARCH");
                break;
            case R.id.homeAppointment:             //约看
                mIntent = new Intent(getActivity(), AppointmentVisitActivity.class);
                break;
            case R.id.homeHousingResource:        //房源
                mIntent = new Intent(getActivity(), HouseRecordAddressActivity.class);
                break;
            case R.id.homePassengerResource:      //客源
                mIntent = new Intent(getActivity(), RecordCustomer1Activity.class);
                break;
            case R.id.homeBusinessHelp:           //业务帮助
                mIntent = new Intent(getActivity(), BusinessHelpActivity.class);
                break;
            case R.id.homePuzzle:                  //拼了
                MultiImageSelector.create(getActivity())
                        .showCamera(true)
                        .count(1)
                        .single()
                        .multi()
                        .origin(mSelectPath)
                        .start(this, 123);
                break;
            case R.id.homeMortgageCalculator:     //房贷计算器
                mIntent = new Intent(getActivity(), CalculatorActivity.class);
                break;
            case R.id.homeContactList:            //通讯录
                mIntent = new Intent(getActivity(), ClientListActivity.class);
                break;
            case R.id.homeClickMe:                //职能部门工作明细
                mIntent = new Intent(getActivity(), WorkDetailsActivity.class);
                break;
            case R.id.noticeBtn:
            case R.id.moreNotice:
                //通告列表
                mIntent = new Intent(getActivity(), NoticeListActivity.class);
                break;
            case R.id.homeAudit:
                //合同审核
                mIntent = new Intent(getActivity(), ContractAuditCoverActivity.class);
                break;
            case R.id.newHouse:
                //新房
                mIntent = new Intent(getActivity(), NewHouseActivity.class);
                break;
            case R.id.accessManager:
                //带看管理
                mIntent = new Intent(getActivity(), AccessManagerActivity.class);
                break;
            case R.id.buyQualification:
                //购房资质
                mIntent = new Intent(getActivity(), BuyQualificationActivity.class);
                break;
            case R.id.questionreplyTextView:
                //问题回复
                mIntent = new Intent(getActivity(), QuestionResponseActivity.class);
                break;
            case R.id.questionbackTextView:
                //意见反馈
                mIntent = new Intent(getActivity(), FbIdeaMainActivity.class);
                break;
            case R.id.qiyuServiceTextView:
                UnicornUtils.openUnicorn(getContext());
                break;
            case R.id.igScanCode:
                //扫码
                checkPermissionAndCamera();
                break;
            default:
                break;
        }
        if (mIntent != null)
            startActivity(mIntent);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123) {
            if (resultCode == RESULT_OK) {
                mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                Intent intent = new Intent(getActivity(), PuzzleActivity.class);
                if (mSelectPath.size() > 0) {
                    intent.putExtra("url", mSelectPath.get(0));
                }
                startActivity(intent);
                mSelectPath.clear();
            }
        }else if (requestCode==101){
            //扫码回调
            if (resultCode ==RESULT_OK && data != null ){
                HmsScan obj = data.getParcelableExtra(ScanUtil.RESULT);
                if (obj != null) {
                    scanCodeLogin(obj.originalValue);
                }
            }
        }else if (requestCode ==102){
            if (resultCode == 102){
                CustomToast.showToast(getContext(),"登录成功！",1500);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        onHomeFragmentShow();
    }

    @Override
    public void onHomeFragmentShow() {
        Context context = getContext();
        if (context == null) {
            return;
        }
        SharePTool.UserInfoBean bean = SharePTool.getUserInfoBean(context);
        String pin = bean.getPin();
        if (StringKit.isEmpty(pin)) {
            return;
        }

        NimIMUtils.login(context, false, pin, new RequestCallbackWrapper<String>() {
            @Override
            public void onResult(int code, String result, Throwable exception) {
                registerIMObservers(true);
                imHasUnread = NimIMUtils.hasUnread();
                showOrHideUnread();
            }
        });

        OkHttpUtils.get()
                .url(ApiConfig.homeRemind)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        messageHasUnread = false;
                        showOrHideUnread();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        Integer data = (Integer) response.get("data");
                        messageHasUnread = data != null && data > 0;
                        showOrHideUnread();
                    }
                });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        registerIMObservers(false);
    }

    private boolean imHasUnread = false; //云信服务器 是否有未读消息
    private boolean messageHasUnread = false;

    private void showOrHideUnread() {
        if (binding == null || binding.navMessageImageView == null) {
            return;
        }
        if (imHasUnread || messageHasUnread) {
            binding.navMessageImageView.setImageResource(R.mipmap.nav_message_unread);
        } else {
            binding.navMessageImageView.setImageResource(R.mipmap.nav_message);
        }
    }


    private Observer<List<IMMessage>> messageObserver = new Observer<List<IMMessage>>() {

        @Override
        public void onEvent(List<IMMessage> imMessages) {
            if (imMessages != null && !imMessages.isEmpty()) {
                binding.navMessageImageView.setImageResource(R.mipmap.nav_message_unread);
                imHasUnread = true;
                showOrHideUnread();
            }
        }
    };

    private void registerIMObservers(boolean register) {
        MsgServiceObserve service = NIMClient.getService(MsgServiceObserve.class);
        service.observeReceiveMessage(messageObserver, register);
    }

    //检查扫码权限
    private void checkPermissionAndCamera() {
        int hasCameraPermission = ContextCompat.checkSelfPermission(getActivity().getApplication(),
                Manifest.permission.CAMERA);
        if (hasCameraPermission == PackageManager.PERMISSION_GRANTED) {
            //有调起相机扫码。
            ScanUtil.startScan(getActivity(), 101,null);
        } else {
            //没有权限，申请权限。
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.CAMERA}, 0x00000012);
        }
    }

    //处理权限申请回调
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 0x00000012) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //允许权限，有调起相机扫码。
                ScanUtil.startScan(getActivity(), 101,null);
            }
        }
    }

    //请求扫码登录接口
    public void scanCodeLogin(String qrcode){
        OkHttpUtils.get()
                .url(ApiConfig.SCANCODELOGIN)
                .addParams("qrcode",qrcode)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                       int  code = Integer.parseInt(String.valueOf(response.get("code")));
                       if (code != 107){
                           Intent intent = new Intent(getContext(),ScanCodeLoginActivity.class);
                           intent.putExtra("qrcode",qrcode);
                           intent.putExtra("code",code);
                           intent.putExtra("message",String.valueOf(response.get("message")));
                           startActivityForResult(intent,102);
                       }else{
                           CustomToast.showToast(getContext(),"用户已离职",1500);
                       }
                    }
                });
    }
}
